package com.zy.dao.impl;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.zy.dao.UserDao;
import com.zy.entity.Customer;
import com.zy.entity.User;
import com.zy.utils.JDBCutil;

public class UserDaoImpl implements UserDao{

	@Override
	public User getUser(String name, String pwd) {
    //写代码
		Connection con=null;
		String url="jdbc:mysql://localhost:3306/mybigdata";
		String user="root";
		String pwd1="123456";
		String sql="SELECT * from t_user WHERE username=? and `password`=?";
		PreparedStatement ps=JDBCutil.getPS(con, url, user, pwd1, sql);
		//设置参数
		try {
			ps.setString(1, name);
			ps.setString(2, pwd);
			//执行
			ResultSet rs=ps.executeQuery();
			User uu=null;
			while(rs.next()){
			uu=new User(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4));
			}
			
			return uu;  //一个方法遇到return 方法就结束了，不会再向下运行了
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public List<User> queryAll() {
		try {
			String sql = "select * from t_user";
			Connection connection = null;
			Properties properties = new Properties();
			InputStream in = CustomerDaoImpl.class.getClassLoader().getResourceAsStream("jdbc.txt");
			properties.load(in);
			PreparedStatement ps = JDBCutil.getPS(connection, properties.getProperty("jdbc.url"),
					properties.getProperty("jdbc.user"), properties.getProperty("jdbc.pwd"), sql);
			
			ResultSet rs = ps.executeQuery();
			List<User> users = new ArrayList<>();
			
			while(rs.next()){
				User user = new User();
				user.setUid(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				user.setAddress(rs.getString(4));
				users.add(user);
			}
			//关闭资源
			JDBCutil.closeAll(rs, ps, connection);
			//返回数据
			return users;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
